﻿var JsonRpcClient = function(config) // url , method ,callback  this there parameters is mandatory
{
	//private data
	var _callbackObj = {};
	var _reqRespMapping = [];
	var _createId = function() 
	{
		return ""+(new Date()).getTime();
	};
	var _send = function(jsonData)
	{		
		var _sync=false;
		if(config.sync) _sync=config.sync;
		
		Ext.Ajax.request({
		    method:'POST',
			url: config.url,
			sync:_sync,
			success: function(res)
			{
				response = Ext.decode(res.responseText);
				_reqRespMapping.remove(response.id);				
				if(config.callback)
				{
				   config.callback(response);				
				}			

			},
			failure: function()
			{
				_reqRespMapping.remove(jsonData.id);
				if(config.callback)
				{
				   config.callback({"error":true,result:''});				
				}	
			},
			jsonData : jsonData,
			headers:{"Content-Type":"application/json-rpc;charset=UTF-8"}
		});
	};
	
	
    this[config.method]=function()
	{
		var id = _createId();
		var args = [];
		for(var i=0;i<arguments.length;i++)
		{
			args[i]=arguments[i];
		}		
		var jsonRpcReq = {
			method: config.method,
			params: args,
			id: id
		};
		_reqRespMapping[id] = jsonRpcReq;
		_send(jsonRpcReq);
	
	}
}

Ext.lib.Ajax.initHeader=function(label, value, isDefault)
        {
            var headerObj = (isDefault) ? this.defaultHeaders : this.headers;

            if (headerObj[label] === undefined) {
                headerObj[label] = value;
            }
            else {

                headerObj[label] = headerObj[label] + "," + value;
            }

            if (isDefault) {
                this.hasDefaultHeaders = true;
            }
            else {
                this.hasHeaders = true;
            }
        }
